package com.daman.db

/**
 * Created by daman on 2015/6/8.
 */
trait DbOps {
  def dbName:String
  val m_id = "id"

  /**
   * find one record by id
   * @param id
   * @return
   */
  def findById(id:Int) = {
    val conn = DBToolkit.getConn()
    val sql = "select * from "+dbName+" where "+m_id+" = ? "
    val result = DBToolkit.readMap(conn,sql,List(id.toString))
    DBToolkit.closeConn(conn)
    result
  }

  /**
   * update one record by it's id
   * @param id
   * @param fields
   * @return
   */
  def updById(id:Int,fields:Map[String,String]) = {
    val conn = DBToolkit.getConn()
    val result = DBToolkit.update(conn,dbName,fields,Map(m_id->id.toString))
    DBToolkit.closeConn(conn)
    result
  }

  /**
   * insert on record into table
   * @param fields
   * @return the auto increment id
   */
  def insert(fields:Map[String,String]) = {
    val conn = DBToolkit.getConn()
    val result = DBToolkit.insertReturnId(conn,dbName,fields)
    DBToolkit.closeConn(conn)
    result
  }

  /**
   *  按分页查询 列表
   * @param offset 分页偏移量
   * @param size   分页 每页大小
   * @return  list[Map]
   */
  def list(offset:Int,size:Int)  = {
    val conn = DBToolkit.getConn()
    val sql = "select * from "+dbName+" limit "+offset+","+size
    val result = DBToolkit.readMap(conn,sql,List())
    DBToolkit.closeConn(conn)
    result
  }

  /**
   * 查询表中所有数据
   * @return List[Map]
   */
  def all()  ={
    val conn = DBToolkit.getConn()
    val sql = "select * from "+dbName
    val result = DBToolkit.readMap(conn,sql,List())
    DBToolkit.closeConn(conn)
    result
  }

}
